package prototipo.server.logic.util;

import java.math.BigDecimal;
import prototipo.server.logic.exception.ExceptionLogic;

/**
 * Class to represent Dinheiro
 * 
 * @author pablo
 * @since 08/11/2009
 */
public class Money implements MoneyIF {

	private BigDecimal value;

	public Money(BigDecimal bigDecimal) throws ExceptionLogic {
		this.setValue(bigDecimal);
	}

	public BigDecimal getValue() {
		return value;
	}

	public void setValue(BigDecimal value) throws ExceptionLogic {
		if (validate(value))
			this.value = value;
	}

	private boolean validate(BigDecimal value) throws ExceptionLogic {
		if (value == null)
			throw new ExceptionLogic("Valor do dinheiro vazio.", new Throwable(
					"BigDecimal value is null."));
		if (value.signum() == -1)
			throw new ExceptionLogic("Valor do dinheiro negativo.",
					new Throwable("BigDecimal value is negative."));
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((value == null) ? 0 : value.hashCode());
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof Money))
			return false;
		Money other = (Money) obj;
		if (value == null) {
			if (other.value != null)
				return false;
		} else if (!value.equals(other.value))
			return false;
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	public String toString() {
		String str = String.format("%.2f", this.value.doubleValue());
		str = str.replace('.', ',');
		int length = str.length();
		for (int i = 6; i < length; i += 4) {
			str = str.substring(0, length - i) + "."
					+ str.substring(length - i, length);
			length++;
		}
		str = "R$" + str;
		return str;
	}

}
